package com.itheima.test02;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/test02")
public class DownloadServlet02 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String path = getServletContext().getRealPath("resources/" + name);
        FileInputStream fis = new FileInputStream(path);

        ServletOutputStream os = response.getOutputStream();
        response.setHeader("content-disposition","attachment;filename="+name);
        byte[] bytes = new byte[1024];
        int b;
        while((b = fis.read(bytes))!=-1){
            os.write(bytes,0,b);
        }
        fis.close();
    }
}
